package guoanmaker.operator.business.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import guoanmaker.operator.business.model.OperatorComplaintType;
import guoanmaker.operator.business.repository.OperatorComplaintTypeRepository;

@Service
public class OperatorComplaintTypeService implements OperatorComplaintTypeServiceInterface {

	@Autowired
	private OperatorComplaintTypeRepository operatorComplaintTypeRepository;
	
	@PersistenceContext
	private EntityManager manager;
	
	@Override
	public int saveOperatorComplaintType(OperatorComplaintType operatorComplaintType) {
		// TODO Auto-generated method stub
		String jpql="select o from OperatorComplaintType o where o.complaintTypeName=:complaintTypeName";
		Query query=manager.createQuery(jpql).setParameter("complaintTypeName", operatorComplaintType.getComplaintTypeName());
		List<OperatorComplaintType> list=query.getResultList();
		if(list!=null&&list.size()==1){
			OperatorComplaintType oct=list.get(0);
			if(operatorComplaintType.getId()==null){
				return -2;
			}
			else if(!operatorComplaintType.getId().equals(oct.getId())){
				return -2;
			}
		}
		operatorComplaintType.setCreatDatetime(new Date());
		operatorComplaintTypeRepository.save(operatorComplaintType);
		return 1;
	}

	@Override
	public Map<String, Object> selectOperatorComplaintType(Integer page, Integer size) {
		// TODO Auto-generated method stub
		Map<String,Object> map=new HashMap<String,Object>();
		String jpql="select new guoanmaker.operator.business.modelnobind.OperatorComplaintTypeMove(o.id,o.complaintTypeName, o.creatDatetime,"
				+ " o.userid, u.username)"
				+ " from OperatorComplaintType o,OperatorUser u where o.userid=u.id order by o.creatDatetime desc";
		Query query=manager.createQuery(jpql);
		int count=query.getResultList().size();
		query.setMaxResults(size).setFirstResult(page*size);
		List<OperatorComplaintType> list=query.getResultList();
		map.put("count", count);
		map.put("list", list);
		return map;
	}

	@Override
	public void deleteOperatorComplaintType(String id) {
		id=id==null?"":id;
		if(!id.equals("")){
			String[] str=id.split(",");
			List<String>  liststr=new ArrayList<String>();
			List<OperatorComplaintType>  lists=new ArrayList<OperatorComplaintType>();
			String ids="";
			OperatorComplaintType operatorComplaintType=null;
			for (int i = 0; i < str.length; i++) {
				operatorComplaintType=new OperatorComplaintType();
				ids=str[i];
				operatorComplaintType.setId(ids);
				lists.add(operatorComplaintType);
				liststr.add(ids);
			}
			operatorComplaintTypeRepository.delete(lists);
		}
		
	}

}
